<template>

	<el-dialog 
		v-model="dialogVisible" 
		:title="dialogTitle" 
		:before-close="closeDialog" 
		class="elDiaLog" 
		lock-scroll
		width="1000px" 
		:close-on-click-modal="false" 
		:close-on-press-escape="false">
		<div class="form-box" v-if="['act_edit','act_add'].includes(dialogStatus)" v-loading="loading2">
			<el-form 
			ref="dataFormRef" 
			:model="formData" 
			:rules="rules" 
			label-width="130px">
			    <el-form-item required label="公文编号" prop="doc_no">
			    	<el-input placeholder="请输入公文编号" v-model="formData.doc_no" />
			    </el-form-item>
			    <el-form-item required label="公文标题" prop="title">
			    	<el-input placeholder="请输入公文标题" v-model="formData.title" />
			    </el-form-item>
				<el-form-item required label="机密程度" prop="level">
					<el-select
					     v-model="formData.level"
					     placeholder="请选择机密程度"
					     class="defalut-width" >
					     <el-option :key="1" label="秘密" :value="1"/>
						 <el-option :key="2" label="机密" :value="2"/>
						 <el-option :key="3" label="绝密" :value="3"/>
					   </el-select>
				</el-form-item>
			    <el-form-item label="公文内容" prop="content">
			    	<editor v-model="formData.content" class="editorCont" />
			    </el-form-item>
			    <el-form-item label="上传附件" prop="files">
			    	<el-upload 
						class="upload-demo" 
						name="file" 
						v-model:file-list="formData.files" 
						action="/api/upload"
			    		:data="{type:'file'}" 
						show-file-list 
						:auto-upload="true" 
						:multiple="true"
			    		:on-success="(response:any, file:any, fileList:any) => {return imageBeforUploadSuccess(response, file, fileList,'files');}"
			    		:on-preview="onFilePreview" :before-upload="imageBeforUpload" :limit="5">
			    		<el-button :disabled="formData.files.length>=5" type="primary">
							<template #icon><i-ep-UploadFilled /></template>上传文件</el-button>
			    		<template #tip>
			    			<div class="el-upload__tip">
			    				<el-text size="small" type="info">{{feilType.pageShow}}</el-text>
			    			</div>
			    		</template>
			    	</el-upload>
			    </el-form-item>
				<el-form-item required label="审批流程" prop="user" >
					<div class="elTimeBox">
						<el-button	
							v-if="approveList.type == 0"
							type="primary" 
							style="margin-bottom: 20px;"
							@click="clickShenPiR('ac_addlist','user')">
								<template #icon><i-ep-CirclePlusFilled /></template>增加一级审批</el-button>
						<el-timeline>
							<el-timeline-item v-for="(item,index) in formData.user">
								<template #dot>
									<div class="el-timeline-item__node el-timeline-item__node--large">
										<el-icon><i-ep-user-filled /></el-icon>
									</div>
								</template>
								<div class="levelC">
									<div class="levelT">
										<h2 class="levelTH2" v-if="approveList.type == 0">第{{index + 1}}级审核人审批</h2>
										<h2 class="levelTH2" v-else>{{item.name}}</h2>
										<el-button v-if="index != 0" @click="delectUserClose(index,'user')" circle style="border: none;" >
											<template #icon><i-ep-Delete /></template>
										</el-button>
									</div>
									<div class="levelP">
										<div v-for="(ites,inds) in item.user_info" class="levelPi">
											<div class="levelPiU">
												<div class="levelPiUImgs">
													<img class="levelPiUImg" :src="ites.avatar" alt="">
												</div>
												<div class="levelPiUName">
													{{ites.name}}
												</div>
											</div>
											<div class="levelDelet"   @click="closeUser(item,index,inds,'user')">
												<i-ep-CircleClose style="width: 14px;" />
											</div>
										</div>
										<div class="levelP_add" >
										
											<el-button  @click="addUser(item,index,'user')" >
												<template #icon><i-ep-CirclePlus /></template>添加
											</el-button>
										</div>
									</div>
								</div>
							</el-timeline-item>
						</el-timeline>
					</div>
				</el-form-item>
			</el-form>
		</div>
		<div class="form-box" v-if="['act_info'].includes(dialogStatus)" v-loading="loading2">

			<el-descriptions size="default" :column="1" border>
				<el-descriptions-item label-class-name="labelC1"
					label="公文编号：">
					<span >{{ dataInfo.title }}</span>
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="公文标题：">
					{{ dataInfo.title }}
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="机密程度：">
					<el-tag v-if="dataInfo.level == 1" type="primary">秘密</el-tag>
					<el-tag v-if="dataInfo.level == 2" type="warning">机密</el-tag>
					<el-tag v-if="dataInfo.level == 3" type="danger">绝密</el-tag>
					<el-tag v-if="dataInfo.level == 0" type="info">未设置</el-tag>
				</el-descriptions-item>
				
				<el-descriptions-item label-class-name="labelC1"
					label="公文内容：">
					<div class="artleCo" v-html="dataInfo.content"> </div>
				</el-descriptions-item>
	
				<el-descriptions-item label-class-name="labelC1"
					label="附件：">
					<div v-if="dataInfo.files?.length >0" 
					v-for="(ite,ind) in dataInfo.files">
						<el-link @click="onFilePreview(ite)" type="primary">{{ind + 1}}.{{ite.name}}</el-link>
					</div>
					<el-text v-else type="info">无</el-text>
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="添加时间：">
					{{ dataInfo.add_time_text }}
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="审核状态：">
	
					<el-tag style="margin-right: 10px;" v-if="dataInfo.is_check == 0" type="info">审核中</el-tag>
					<el-tag style="margin-right: 10px;" v-if="dataInfo.is_check == 1" type="success">已通过</el-tag>
					<el-tag style="margin-right: 10px;" v-if="dataInfo.is_check == 2" type="danger">已驳回</el-tag>
					<el-text style="margin-left: 5px;" v-if="dataInfo.is_check == 2 ||dataInfo.is_check == 1 "  type="primary">{{dataInfo.check_time_text}}</el-text>
				</el-descriptions-item>
				
				
				
			</el-descriptions>	
			
			<template v-if="dataInfo.approve?.rule?.length>0">
				<el-divider content-position="left">审批日志</el-divider>
				<el-row>
					<div class="uTCont" v-for="uItem in dataInfo.approve?.rule" style="width: 100%;">
						<h4 class="uThead">{{uItem.name}}</h4>
						<el-table border  :data="uItem.user_info" style="width: 100%">
						<el-table-column label="审批人" width="200">
							<template #default="scope">
								<div class="uhead">
									<el-avatar :size="40" :src="scope.row.avatar" ></el-avatar>
									<span class="uheadN">{{scope.row.name}}</span>
								</div>
							</template>
						</el-table-column>
						<el-table-column label="审核状态" align="center" width="150">
							<template #default="scope">
								<el-tag v-if="scope.row.status == 0" type="info">待审核</el-tag>
								<el-tag v-if="scope.row.status == 1" type="success">已通过</el-tag>
								<el-tag v-if="scope.row.status == 2" type="danger">已驳回</el-tag>
							</template>
						</el-table-column>
						<el-table-column label="操作日期" width="220">
							<template #default="scope">
								<el-icon> <el-icon-timer></el-icon-timer></el-icon>
								<span style="margin-left: 10px">{{ scope.row.check_time }}</span>
							</template>
						</el-table-column>
						<el-table-column label="备注">
							<template #default="scope">
								{{ scope.row.mark }}
							</template>
						</el-table-column>
					</el-table> 
					</div>
				</el-row>
			</template>
		</div>
		<div class="form-box" v-if="['act_pre'].includes(dialogStatus)" v-loading="loading2">
			 <div class="aletlCo" >
			  <div class="artleTi">
			    <h2 class="artleTiH2">{{ dataInfo.title }}</h2>
			    <div class="artleTiCo">
			      <span class="artBs">发布时间：{{ dataInfo.add_time_text }}</span>
			    </div>
			  </div>
			  <div class="artleCo" v-html="dataInfo.content"> </div>
			  <div v-if="dataInfo.files?.length > 0">
			    <div class="fujian">
			      附件下载
			    </div>
			    <ul >
			      <li v-for="(item,index) in dataInfo.files">
			        <el-link :download="item.name" class="fujiana" :href="item.url" :icon="Edit">{{ item.name }}</el-link>
			      </li>
			    </ul>
			  </div>
			</div> 

		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button v-if="['act_info','act_pre'].includes(dialogStatus)" :disabled="loading3" @click="closeDialog">关
					闭</el-button>
				<el-button v-if="['act_edit','act_add'].includes(dialogStatus)" type="primary" 
					 v-no-more-click 
					@click="handleSubmit">{{dialogStatus == 'act_edit'?'重新提交':'确 定'}}</el-button>
				<el-button v-if="['act_edit','act_add'].includes(dialogStatus)" :disabled="loading3"
					@click="closeDialog">取 消</el-button>
			</div>
		</template>

		<!-- 选择审批人信息 -->
		<el-dialog v-model="dialogTree.visible" class="elDiaLog" lock-scroll title="选择审核人" width="1000px"
			@close="closeDialogTree">
			<div style="min-height: 300px;">
				<el-tree ref="treeRef" 
					node-key="id" 
					:data="options" 
					:default-expanded-keys="[1]"
					:check-on-click-node="true" 
					:show-checkbox="true"
					:props="{'children': 'children','label':'name','value':'id','disabled':'disable'}">
					<template #default="{ node, data }">
						<treeBlock :nodeItem="node" :dataItem="data" :typeClass="1"></treeBlock>
					</template>
				</el-tree>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="getAllkeys">确定</el-button>
					<el-button @click="closeDialogTree">取消</el-button>
				</div>
			</template>
		</el-dialog>
	</el-dialog>
</template>
<script setup lang="ts">
	import { useRoute } from 'vue-router';
	import _ from 'lodash-es'
	import { feilType, onFilePreview } from "@/utils/funcall"
	import { useBaseConfigStore } from "@/store/modules/baseConfig";
	const baseConfigStore = useBaseConfigStore();
	import Editor from "@/components/WangEditor/index.vue";
	
	//接口地址
	import {
		addDoc,
		updataDoc,
		getDoc,
		getDepartmentAndUser
	} from "@/api/doc";

	const props = defineProps({
		//数据列表索引值  例如 user ->对应着 vuex  == user_cxxxxx模块
		dialogTitle: {
			type: String,
			default: "添加信息"
		},
		dialogStatus: {
			type: String,
			default: "act_add"
		},
		dialogTableValue: {
			type: Object,
			default: () => { },
		},
		approveList:{
			type:Object,
			default: () => { },
		}
	});
	
	const emit = defineEmits(['update:modelValue', 'initRefreshList']);
	const dialogVisible = ref(false);
	const loading2 = ref(false);//新增或者修改加载load按钮
	const loading3 = ref(false);//新增或者修改加载load按钮
	// 数据的data-ref
	const dataFormRef = ref(ElForm);
	const dataInfo = ref<any>({});
	const formData = ref<any>({
		id: undefined,
		doc_no:"",//公文编号
		title:"",//公文标题
		level:"",//机密程度
		content:"",//公文内容
		files:[],//公文附件
		user:[[]]//审批流
	})
	const rules = reactive<any>({
		doc_no: [{ required: true, message: "请填写编号", trigger: "blur" }],
		title: [{ required: true, message: "请填写标题", trigger: "blur" }],
		level:[{ required: true, message: "请选择机密程度", trigger: "change" }],
		user:[{required: true,  validator: userValidator, trigger: "blur"}]
	})
	/**
	 * 审批人校验器
	 */
	function userValidator(rule: any, value: any, callback: any) {
		if (!value || value.length === 0) {
			return callback(new Error("请选择审批人"));
		}
		const hasEmptyValue = value.some(item => item.length === 0);
		if (hasEmptyValue) {
			return callback(new Error("请选择审批人"));
		}
		return callback();
	}

	watch(
		() => props.dialogTableValue,
		() => {
			if (props.dialogStatus == "audit_art") {
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else if (props.dialogStatus == "act_info"  ) {
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else if (props.dialogStatus == "act_edit" ) {
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else if(props.dialogStatus =="act_pre")
			{
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else {
				formData.value.user = JSON.parse(JSON.stringify(props.approveList.rule));
			}
		}, { deep: true, immediate: true })

	// 提交新增内容/or修改
	function handleSubmit() {
		dataFormRef.value.validate((valid : boolean) => {
			if (valid) {
				loading3.value = true;
				const rules = []
				for(var i = 0 ; i <formData.value.user.length;i++)
				{
					const item = formData.value.user[i]
					if(props.approveList.type==1)
					{
						rules.push({
							name:item.name,
							type:item.type,
							level:item.level,
							user:item.user_info.map(userObj => userObj.uid)
						})
					}
					else
					{
						rules.push({
							name:`第${i + 1}级审批人审批`,
							type:0,
							level:0,
							user:item.user_info.map(userObj => userObj.uid)
						})
					}
				}

				let data : any = {
					id: formData.value.id,
					doc_no:formData.value.doc_no,
					title:formData.value.title,
					level:formData.value.level,
					content:formData.value.content,
					files:formData.value.files,
					rule:rules
				}

				if (formData.value.id) {
					ElMessageBox.confirm("修改信息会将进行审批?", "警告", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning",
					}).then(() => {
						updataDoc(data).then((res) => {
							console.log(res)
							emit('initRefreshList');
							loading3.value = false;
							ElMessage({ message: '修改成功', type: 'success' ,duration:1000})
							closeDialog();
						}).finally(() => {
							loading3.value = false;
						})
					}).catch(() => {
						loading3.value = false;
					});
				}
				else {
					addDoc(data).then((res) => {
						console.log(res)
						emit('initRefreshList');
						loading3.value = false;
						ElMessage({ message: '添加成功', type: 'success' ,duration:1000})
						closeDialog();
					}).finally(() => {
						loading3.value = false;
					})
				}
			}
		});
	}



	// 关闭弹窗
	function closeDialog() {
		if (!loading3.value) {
			emit('update:modelValue', false)
		}
	}

	// 获取详情
	function getAuditDetail(row) {
		console.log(row)
		loading2.value = true;
		getDoc({ id: row.id }).then((res) => {
			let data = res.data;
			formData.value.id = data.id;
			formData.value.doc_no = data.doc_no;
			formData.value.title = data.title;
			formData.value.level = data.level==0?"":data.level;
			formData.value.content = data.content;
			formData.value.files = data.files;
			formData.value.user = data.approve.rule;
			dataInfo.value = res.data;
			
			
		}).finally(() => {
			loading2.value = false;
		})
	}

	// 审批流相关的代码 start
	const dialogTree = reactive<DialogOption>({
		visible: false,
	});
	const options = ref();
	const defaultUserKey = ref({
		type: "",
		userkey: [],
		index: -1
	});
	const treeRef = ref();
	/**
	 * 添加审批人
	 */
	function clickShenPiR(type : string, el : any, index ?: any) {
		if (type == "ac_delect") {
			formData.value[el].splice(index, 1)
		}
		else if (type == "ac_addlist") {
			formData.value[el].push({name: "",user_info:[]})
		}
	}
	/**
	 * 打开弹窗添加审批流信息
	 */
	function addUser(e : any, index : number, type : string) {
	
		defaultUserKey.value.userkey = e.user_info.map((item : any) => '1_' + item.uid);
		defaultUserKey.value.type = type;
		defaultUserKey.value.index = index
		dialogTree.visible = true;
		nextTick(() => {
			treeRef.value!.setCheckedKeys(defaultUserKey.value.userkey, false)
		})
	}
	// 删除审批人-组
	function delectUserClose(index:any,type:any){
		const items = formData.value[type];
		if (items.length > 1) {
			items.splice(index, 1);
		}
	}
	/**
	 * 删除审批人-人
	 */
	function closeUser(e : any, index : number, inds : number, type : string) {
		formData.value[type][index]['user_info'].splice(inds, 1);
	}
	function getAllkeys() {
	
		formData.value[defaultUserKey.value.type][defaultUserKey.value.index]['user_info'] = treeRef.value!.getCheckedNodes(true);
		closeDialogTree();
	}
	/**
	 * 获取审批人列表
	 */
	function getShenPlist() {
		getDepartmentAndUser().then((res) => {
			options.value = res.data
		}).finally(() => { })
	}
	/**
	* 关闭 树形图 弹窗
	*/
	function closeDialogTree() {
		dialogTree.visible = false;
	}
	// 审批流相关的代码 End

	/**
	 * 上传文件 之前的操作
	 */
	function imageBeforUpload(file : any) {
		var fileSize = file.size / 1024 / 1024 < feilType.size;
		const index = file.name.lastIndexOf(".");
		const ext = file.name.substr(index + 1).toUpperCase();
		if (feilType.extarr.indexOf(ext) == -1) {
			ElMessage({
				message: feilType.errorMes,
				type: 'error',
			})
			return false;
		}
		if (!fileSize) {
			ElMessage({
				message: feilType.prompt,
				type: 'error',
			})
			return false;
		}
	}
	// 图片和文件类型上传成功之后的回调
	function imageBeforUploadSuccess(response : any, file : any, fileList : any, el : any) {
		console.log(response, file, fileList, el)
		formData.value[el] = formData.value[el].map(item => {
			if (item.uid == file.uid) {
				const obj : any = {}
				obj.uid = file.uid
				obj.url = response.data.url
				obj.name = file.name
				return obj;
			}
			else {
				return item;
			}
		});
	}
	
	
	onMounted(() => {
		getShenPlist();
		
	});
</script>

<style lang="scss" scoped>
.editorCont {
		min-height: 500px
	}

	.atcBox {
	  background: #ffffff;
		width: 100%;
	  margin: 0 auto;
	  padding: 30px 40px;
	  background: #fff;
	  box-sizing: border-box;
	}
	
	.aletlCo {
	  width: 100%;
	 
	  .artleTi {
	    border-bottom: 1px solid #bfbfbf;
	    padding: 8px 0;
	    .artleTiH2 {
	      font-size: 22px;
	      color: #333333;
	      text-align: center;
	      line-height: 28px;
	      font-weight: bold;
	      margin-bottom: 8px;
	    }
	    .artleTiCo {
	      display: flex;
	      justify-content: center;
	      flex-wrap: wrap;
	      .artBs {
	        margin-right: 20px;
	      }
	
	    }
	  }
	  .artleCo {
	    line-height: 2;
	    font-size: 16px;
	    padding: 25px 0;
	  }
	}
	
	.fujian{
	  font-size: 14px;
	  line-height: 30px;
	}
	.fujiana{
	    background-size: 20px 25px;
	    cursor: pointer;
	    color: #2379f7;
	}
	
	.shBox{
	  display: flex;
	  justify-content: space-between;
	 
	  box-sizing: border-box;
	  margin-top: 30px;
	}
</style>